//
//  UserManager.swift
//  用户管理器
//
//  Created by smile on 2019/7/23.
//  Copyright © 2019 ixuea. All rights reserved.
//

import Foundation

//导入响应式编程框架
import RxSwift

class UserManager {
    
    /// 单例
    private static var instance:UserManager?
    
    //负责对象销毁
    //这个功能类似NotificationCenter的removeObserver
    let disposeBag=DisposeBag()
    
    /// 用户缓存列表
    var userCaches:[String:User]=[:]
    
    /// 获取用户管理器
    ///
    /// - Returns: <#return value description#>
    static func shared() -> UserManager {
        if instance==nil {
            instance=UserManager()
        }
        
        return instance!
    }
    
    /// 根据Id获取用户
    ///
    /// - Parameters:
    ///   - id: <#id description#>
    ///   - success: <#success description#>
    func getUser(_ id:String,success:@escaping (_ data:User)->Void) {
        //先从缓存获取
        let data=userCaches[id]
        
        if let data = data {
            //有数据
            
            //直接回调
            success(data)
            return
        }
        
        //没有用户
        
        //请求接口
        Api.shared.userDetail(id: id).subscribeOnSuccess { (data) in
            if let data=data?.data{
                //将用户保存到缓存列表
                self.userCaches[id]=data
                
                //回调
                success(data)
            }
        }.disposed(by: disposeBag)
    }
}
